package it.units.dacuts.image;

import it.units.dacuts.utility.Check;
import java.util.Arrays;

public class ArrayImage implements Image {
    
    private final int width;
    private final int height;
    private final int[] data;
    
    public ArrayImage(int width, int height) {
        Check.argument(width > 0, "width is not positive");
        Check.argument(height > 0, "height is not positive");
        this.width = width;
        this.height = height;
        data = new int[width * height];
        Arrays.fill(data, ARGBChannel.ALPHA.setValueToARGB(0xFF, 0));
    }
    
    public ArrayImage(Image image) {
        Check.notNull(image, "image is null");
        width = image.getWidth();
        height = image.getHeight();
        data = new int[width * height];
        for (int y = 0; y < height; y++)
            for (int x = 0; x < width; x++)
                data[y * width + x] = ARGBChannel.ALPHA.setValueToARGB(0xFF, image.getPixelRGBValue(x, y));
    }

    @Override
    public int getWidth() {
        return width;
    }

    @Override
    public int getHeight() {
        return height;
    }

    @Override
    public int getPixelRGBValue(int x, int y) {
        Check.index(x).inBounds(0, width, "index x out of bounds");
        Check.index(y).inBounds(0, height, "index y out of bounds");
        return data[y * width + x];
    }

    @Override
    public int getPixelRedValue(int x, int y) {
        return ARGBChannel.RED.getValueFromARGB(getPixelRGBValue(x, y));
    }

    @Override
    public int getPixelGreenValue(int x, int y) {
        return ARGBChannel.GREEN.getValueFromARGB(getPixelRGBValue(x, y));
    }

    @Override
    public int getPixelBlueValue(int x, int y) {
        return ARGBChannel.BLUE.getValueFromARGB(getPixelRGBValue(x, y));
    }
    
    public void setPixelRGBValue(int x, int y, int argb) {
        Check.index(x).inBounds(0, width, "index x out of bounds");
        Check.index(y).inBounds(0, height, "index y out of bounds");
        data[y * width + x] = ARGBChannel.ALPHA.setValueToARGB(0xFF, argb);
    }

    public void setPixelRedValue(int x, int y, int value) {
        setPixelRGBValue(x, y, ARGBChannel.RED.setValueToARGB(value, getPixelRGBValue(x, y)));
    }

    public void setPixelGreenValue(int x, int y, int value) {
        setPixelRGBValue(x, y, ARGBChannel.GREEN.setValueToARGB(value, getPixelRGBValue(x, y)));
    }

    public void setPixelBlueValue(int x, int y, int value) {
        setPixelRGBValue(x, y, ARGBChannel.BLUE.setValueToARGB(value, getPixelRGBValue(x, y)));
    }
}
